<?php
/* Marc Binns 11.09.2010
 * Collection of Battle related functions
 */
class BattleCommand{


	/**
	 * Creates a new Battle Instance with the Given Name & Password(If given)
	 * Also adds the host to the Battle and sets the battles state to 0=Staging
	 *
	 * @param array $request ['P'=PlayerId, 'Bn'=BattleName varchar(16), 'Pwd'=Password (Send as empty string if not required)
	 * @return array 'B'=NewBattleId
	 */
	public function createBattleInstance(array $request){
		require_once(DirectoryManager::$pathCore."/Database.php");

		//Escape harmful chars ================================================
		//TODO MARC: Take MySQL illegal char escaping into use!
		//$request = Database::EscapeParamArray($request);

		//Update Password param to NULL if empty string =======================
		If(array_key_exists('Pwd',$request)){
			If(empty($request['Pwd'])) {
				$password = 'NULL';
			}Else{
				$password = "'".$request['Pwd']."'";
			}

		}Else{
			$password = 'NULL';
		}

		//Convert request to DB Friendly Order ================================
		$params = array($request['P'], "'".$request['Bn']."'", $password);

		//Contact DB and execute Proc =========================================
		$db = Database::getInstance();
		$result = $db->callSP(SiteConfig::sP_Battle_Create, $params);
		$result = $result[0];

		//VERY basic error checking
			If(!empty($result)){
				If($result[0] != -1){
				//Convert result to return friendly
				$return = array("B" => $result['NewBattleId'], "ts"=>$result['NewTsUNIX']);
				return $return;

				}Else{
					throw new exception("Unable to create new battle instance in 'BattleCommand > Create'");
				}

			}Else{
				throw new exception("Unable to create new battle instance in 'BattleCommand > Create'");
			}
	}

	/**
	 * Get updates on all units since the provided timestamp
	 *
	 * @param array $request ['B'=BattleId, 'ts'=LastPolledTimeStamp OR Base 1262304000]
	 * @return array $return [All Unit Rows in seperate arrays plus 'ts'=LatestSeverTimeStamp]
	 * See code for breakdown
	 */
	public function GetUpdates(array $request){
		require_once(DirectoryManager::$pathCore."/Database.php");

//		//### DEBUG ###
//		$debug = "DEBUG: ";
//		foreach($request As $key => $value){
//			$debug = $debug."[".$key."]=".print_r($value,true);
//		}
//		throw new exception($debug);

		//Escape harmful chars ============================================
		//TODO MARC: Take MySQL illegal char escaping into use!
		//$request = Database::EscapeParamArray($request);

		//Convert request to DB Friendly ==================================
		$params = array($request['B'], $request['ts']);

		//Contact DB and execute Proc =====================================
		$db = Database::getInstance();
		$rows = $db->callSP(SiteConfig::sP_Battle_GetUpdates, $params);

		//VERY basic error checking =======================================
		Try{
			$return = array();
			If($rows And $rows[0] != -1){
				//Convert result to return friendly
				foreach($rows as $row){
					$convertedRow = array(
					"U" => $row['Id'],
					"TYP" => $row['UnitTypeId'],
					"P" => $row['PlayerId'],
					"T" => $row['TeamId'],
					"at" => $row['ActiveTurn'],
					"MT" => $row['MovementType'],
					"mlt" => $row['MovedLastTurn'],
					"c" => $row['UnitCallsign'],
					"f" => $row['UnitTile'],
					"x" => $row['X'],
					"y" => $row['Y'],
					"r" => $row['UnitTileBearing'],
					"hp" => $row['HP'],
					"sp" => $row['SP'],
					"mp" => $row['APMove'],
					"ap" => $row['APAttack'],
					"W1" => $row['Weapon1Id'],
					"W2" => $row['Weapon2Id'],
					"W3" => $row['Weapon3Id'],
					"W4" => $row['Weapon4Id'],
					"W5" => $row['Weapon5Id'],
					"W6" => $row['Weapon6Id'],
					"a1" => $row['Ammo1'],
					"a2" => $row['Ammo2'],
					"a3" => $row['Ammo3'],
					"a4" => $row['Ammo4'],
					"a5" => $row['Ammo5'],
					"a6" => $row['Ammo6'],
					"ts" => $row['NewTsUNIX']);

					array_push($return, $convertedRow);
				}
//				//### DEBUG ###
//				$debug = "DEBUG: ";
//				foreach($rows As $key => $value){
//					$debug = $debug."[".$key."]=".print_r($value,true);
//				}
//				throw new exception($debug);
				return $return;

			}Else{
				$return = array(-1);
				return $return;
			}
		}Catch(Exception $e){
			//TODO Marc: Do we want to silence all errors and just return this?
			throw new exception("Unable to get battle updates in 'BattleCommand > GetUpdates'");
		}
	}

	/**
	 * End the players turn and activate all next turn players units
	 *
	 * @param array $request
	 * @return array
	 */
	public function EndTurn(array $request){
		require_once(DirectoryManager::$pathCore."/Database.php");

		//Escape harmful chars ============================================
		//TODO MARC: Take MySQL illegal char escaping into use!
		//$request = Database::EscapeParamArray($request);

		//Convert request to DB Friendly ==================================
		$params = array($request['B'],$request['P']);

		//Contact DB and execute Proc =====================================
		$db = Database::getInstance();
		$rows = $db->callSP(SiteConfig::sP_Battle_EndTurn, $params);
		$rows = $rows[0];

		//VERY basic error checking =======================================
		Try{
			If($rows And $rows[0] != -1){
				//Convert result to return friendly
				$return = array("P" => $rows["NewTurnPlayerId"]);
				return $return;

			}Else{
				throw new exception("Unable to End Player Turn in 'BattleCommand > EndTurn'");
			}
		}Catch(Exception $e){
			//TODO Marc: Do we want to silence all errors and just return this?
			throw new exception("Unable to End Player Turn in 'BattleCommand > EndTurn'");
		}
	}

	/**
	 * Start a battle instance if not already started
	 * Also retrieves ALL unit & player info rows
	 *
	 * @param array $request ['B'=BattleId]
	 * @return array $return ['units'=>$unitRows, 'players'=>$playerRows]
	 */
	public function Start(array $request){
		require_once(DirectoryManager::$pathCore."/Database.php");

		//Escape harmful chars ============================================
		//TODO MARC: Take MySQL illegal char escaping into use!
		//$request = Database::EscapeParamArray($request);

		//Convert request to DB Friendly ==================================
		$params = array("B"=>$request['B']);

		//Contact DB and execute Proc =====================================
		$db = Database::getInstance();
		$rows = $db->callSP(SiteConfig::sP_Battle_Start, $params);
		$rows = $rows[0];

		$return = array("B"=>$rows["TargetBattleId"], "SP"=>$rows["TargetStartingPlayerId"]);
		return $return;
	}


	/**
	 * Fetches all Player detail rows from the Status_Battle Table
	 * Used for connectToGameAction
	 *
	 * @param array $request ['B'=BattleId]
	 * @return array $return [All related Status_Battle rows (i.e. Player Info)]
	 */
	public function GetPlayersInfo(array $request){
		require_once(DirectoryManager::$pathCore."/Database.php");

		//Escape harmful chars ============================================
		//TODO MARC: Take MySQL illegal char escaping into use!
		//$request = Database::EscapeParamArray($request);

		//Convert request to DB Friendly ==================================
		$params = array("B"=>$request['B']);

		//Contact DB and execute Proc =====================================
		$db = Database::getInstance();
		$rows = $db->callSP(SiteConfig::sP_Battle_GetPlayerInfo, $params);

		//Covert Rows to return friendly ==================================
		$return = array();
		foreach($rows as $row){
			$convertedRow = array(
				"B" => $row["Id"],
				"Bn" => $row["BattleName"],
				"Mp" => $row["MaxPlayers"],
				"M" => $row["MapId"],
				"Mn" => $row["MapName"],
				"S" => $row["State"],
				"T" => $row["TeamId"],
				"P" => $row["PlayerId"],
				"Pn" => $row["PlayerName"]);

			array_push($return, $convertedRow);
		}
		return $return;
	}

	/**
	 * Destroy a Battle instance and all related rows. Also updates the result of the battle to player table
	 *
	 * @param array $request
	 * @return array
	 */
	public function Kill(array $request){
		require_once(DirectoryManager::$pathCore."/Database.php");

		//Escape harmful chars ============================================
		//TODO MARC: Take MySQL illegal char escaping into use!
		//$request = Database::EscapeParamArray($request);

		//Convert request to DB Friendly ==================================
		$params = array($request['B'],$request['c1'],$request['c2']);

		//Add Optional Params =============================================
		If(array_key_exists('c3',$request)){
			array_push($params, $request['c3']);
		}Else{
			array_push($params, 'NULL');
		}
		If(array_key_exists('c4', $request)){
			array_push($params, $request['c4']);
		}Else{
			array_push($params, 'NULL');
		}

		//Contact DB and execute Proc =====================================
		$db = Database::getInstance();
		$rows = $db->callSP(SiteConfig::sP_Battle_Kill, $params);

		//VERY basic error checking =======================================
		Try{
			If($rows And $rows[0] != -1){
				//TODO Do we even need a return for battle_Kill?
				return $return;
			}Else{
				throw new exception("Unable to Kill Battle instance 'BattleCommand > Kill'");
			}
		}Catch(Exception $e){
			//TODO Marc: Do we want to silence all errors and just return this?
			throw new exception("Unable to Kill Battle instance 'BattleCommand > Kill'");
		}
	}

}
?>